package com.pi.stroop.controller;

import com.pi.base.util.ExcelUtil;
import com.pi.base.util.POIParam;
import com.pi.base.util.SysGridField;
import com.pi.base.util.SysGridInfo;
import com.pi.stroop.model.diagnosis.DiagnosisDetailResult;
import com.pi.stroop.model.diagnosis.DiagnosisFullResult;
import com.pi.stroop.model.diagnosis.DiagnosisTaskDetail;
import com.pi.stroop.service.StroopDiagnosisService;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/diagnosis/record")
@Controller
public class StroopDiagnosisController {
    private static final Logger logger =
            LoggerFactory.getLogger(StroopDiagnosisController.class);
    @Autowired
    private StroopDiagnosisService diagnosisService;

    @RequestMapping("/list")
    public String list() {
        return "stroop/diagnosis/record/list";
    }

    @RequestMapping("/list/query")
    @ResponseBody
    public Map<String, Object> query(Long userId, Integer page, Integer rows) {
        Map<String, Object> map = new HashMap<>();
        List<DiagnosisDetailResult<DiagnosisTaskDetail>> list =
                diagnosisService.queryPartnerDiagnosisDetailHistory(userId, rows, page);
        Long count = diagnosisService.queryPartnerDiagnosisDetailHistoryCount(userId);
        map.put("total", count);
        map.put("rows", list);
        return map;
    }

    @RequestMapping("/list/export")
    public void export(Long userId, Integer page, Integer rows, HttpServletResponse response) {
        List<DiagnosisDetailResult<DiagnosisTaskDetail>> list =
                diagnosisService.queryPartnerDiagnosisDetailHistory(userId, 1000, 1);
        SysGridInfo sysGridInfo =
                getSysGridInfo(list.get(0).getDiagnosisDate(), list.get(list.size() - 1).getDiagnosisDate());
        Workbook workBook = null;
        try {
            workBook = ExcelUtil.importStandardData(list, sysGridInfo);

            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", "attachment; filename=" + (System.currentTimeMillis() / 1000) + ".xls");

            workBook.write(response.getOutputStream());

        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (null != workBook) {
                try {
                    workBook.close();
                } catch (IOException e) {
                    logger.error("excel流关闭失败", e);
                }
            }
            try {
                response.flushBuffer();
            } catch (IOException e) {
                logger.error("输出文件失败", e);
            }
        }
    }

  @RequestMapping("/list/export/full")
  public void exportFull(Long userId, Integer page, Integer rows, HttpServletResponse response) {
      List<DiagnosisFullResult> list = diagnosisService.queryPartnerDiagnosisFullHistory(userId, 1000, 1);
      SysGridInfo sysGridInfo =
              getFullSysGridInfo(list.get(0).getDiagnosisDate(), list.get(list.size() - 1).getDiagnosisDate());
    Workbook workBook = null;
    try {
      workBook = ExcelUtil.importStandardData(list, sysGridInfo);

      response.setContentType("APPLICATION/OCTET-STREAM");
      response.setHeader("Content-Disposition", "attachment; filename=" + (System.currentTimeMillis() / 1000) + ".xls");

      workBook.write(response.getOutputStream());

    } catch (Exception e) {
      logger.error("", e);
    } finally {
      if (null != workBook) {
        try {
          workBook.close();
        } catch (IOException e) {
          logger.error("excel流关闭失败", e);
        }
      }
      try {
        response.flushBuffer();
      } catch (IOException e) {
        logger.error("输出文件失败", e);
      }
    }
  }

    private List<SysGridField> getDiagnosisFieldList() {
        List<SysGridField> fields = new ArrayList<SysGridField>();
        SysGridField field1 = new SysGridField("diagnosisDate", "诊断日期", 200);
        SysGridField field2 = new SysGridField("userName", "姓名", 200);
        SysGridField field3 = new SysGridField("diagnosisLevel", "结果", 200);
        SysGridField field4 = new SysGridField("delayPeriod", "响应延迟", 200);
        SysGridField field5 = new SysGridField("reactPeriod", "反应时间", 200);
        SysGridField field6 = new SysGridField("interference", "正确数干扰量", 200);
        SysGridField field7 = new SysGridField("inviterName", "邀请人", 200);
        fields.add(field1);
        fields.add(field2);
        fields.add(field3);
        fields.add(field4);
        fields.add(field5);
        fields.add(field6);
        fields.add(field7);
        return fields;
    }

    private List<SysGridField> getDiagnosisSubList() {
        List<SysGridField> fields = new ArrayList<SysGridField>();
        SysGridField field1 = new SysGridField("taskName", "任务名称", 200);
        SysGridField field2 = new SysGridField("totalTime", "总时间", 200);
        SysGridField field3 = new SysGridField("errorCount", "错误数", 200);
        SysGridField field4 = new SysGridField("correctCount", "正确数", 200);
        SysGridField field5 = new SysGridField("misCount", "错过数", 200);
        SysGridField field6 = new SysGridField("originData", "原始数据", 200);

        fields.add(field1);
        fields.add(field2);
        fields.add(field3);
        fields.add(field4);
        fields.add(field5);
        fields.add(field6);
        return fields;
    }

    private SysGridInfo getSysGridInfo(String startDate, String endDate) {
        POIParam param = new POIParam();
        param.setTitle("测试记录导出");
        param.setStartDate(startDate);
        param.setEndDate(endDate);
        SysGridInfo root = new SysGridInfo();
        SysGridInfo child = new SysGridInfo();
        root.setGridList(getDiagnosisFieldList());
        child.setGridList(getDiagnosisSubList());
        root.setChildGrid(child);
        root.setPoiParam(param);
        return root;
    }

    private static List<SysGridField> getFullDiagnosisFieldList() {
        List<SysGridField> fields = new ArrayList<SysGridField>();
        SysGridField field1 = new SysGridField("diagnosisDate", "诊断日期", 200);
        SysGridField field2 = new SysGridField("userName", "姓名", 200);
        SysGridField field3 = new SysGridField("userAge", "年龄", 200);
        SysGridField field4 = new SysGridField("userSex", "性别", 200);
        SysGridField field5 = new SysGridField("education", "学历", 200);
        SysGridField field6 = new SysGridField("userMobile", "联系方式", 200);
        SysGridField field7 = new SysGridField("aCorrect", "色词A正确数", 200);
        SysGridField field8 = new SysGridField("aWrong", "色词A错误数", 200);
        SysGridField field9 = new SysGridField("aMiss", "色词A未应答", 200);
        SysGridField field10 = new SysGridField("aTime", "色词A用时", 200);
        SysGridField field11 = new SysGridField("bCorrect", "色词B正确数", 200);
        SysGridField field12 = new SysGridField("bWrong", "色词B错误数", 200);
        SysGridField field13 = new SysGridField("bMiss", "色词B未应答", 200);
        SysGridField field14 = new SysGridField("bTime", "色词B用时", 200);
        SysGridField field15 = new SysGridField("cCorrect", "色词C正确数", 200);
        SysGridField field16 = new SysGridField("cWrong", "色词C错误数", 200);
        SysGridField field17 = new SysGridField("cMiss", "色词C未应答", 200);
        SysGridField field18 = new SysGridField("cTime", "色词C用时", 200);
        SysGridField field19 = new SysGridField("errorCount", "总错误数", 200);
        SysGridField field20 = new SysGridField("totalTime", "总耗时", 200);
        SysGridField field21 = new SysGridField("reactPeriod", "反应时间", 200);
        SysGridField field22 = new SysGridField("reactPeriod", "时间干扰量", 200);
        SysGridField field23 = new SysGridField("interference", "正确数干扰量", 200);
        SysGridField field24 = new SysGridField("diagnosisLevel", "结果", 200);
        fields.add(field1);
        fields.add(field2);
        fields.add(field3);
        fields.add(field4);
        fields.add(field5);
        fields.add(field6);
        fields.add(field7);
        fields.add(field8);
        fields.add(field9);
        fields.add(field10);
        fields.add(field11);
        fields.add(field12);
        fields.add(field13);
        fields.add(field14);
        fields.add(field15);
        fields.add(field16);
        fields.add(field17);
        fields.add(field18);
        fields.add(field19);
        fields.add(field20);
        fields.add(field21);
        fields.add(field22);
        fields.add(field23);
        fields.add(field24);
        return fields;
    }

    private static SysGridInfo getFullSysGridInfo(String startDate, String endDate) {
        POIParam param = new POIParam();
        SysGridInfo root = new SysGridInfo();
        root.setGridList(getFullDiagnosisFieldList());
        root.setPoiParam(param);
        root.setInitDefaultTitle(false);
        return root;
    }
}
